﻿using AutoMapper;
using B.S.BaseData.Domain;
using B.S.BaseData.ErrorCode;
using B.S.BaseData.Infrastructure.Interfaces;
using B.S.BaseData.ReadAPI.Applications.Commands.CarAndPeopleCommand;
using B.S.BaseData.ReadAPI.Dtos;
using MediatR;

namespace B.S.BaseData.ReadAPI.Applications.CommandHandlers.CarAndPeopleCommandHandler
{
    public class PeopelCommandHandler:IRequestHandler<PeopleCommand, ApiResult<List<CarAndPeopleRespDto>>>
    {
        IBaseRepository<Car> carrepositoy;
        IBaseRepository<People> peoplerepository;
        IMapper mapper;
        ILogger<PeopelCommandHandler> logger;

        public PeopelCommandHandler(IBaseRepository<Car> carrepositoy, IBaseRepository<People> peoplerepository, IMapper mapper, ILogger<PeopelCommandHandler> logger)
        {
            this.carrepositoy = carrepositoy;
            this.peoplerepository = peoplerepository;
            this.mapper = mapper;
            this.logger = logger;
        }

        public async Task<ApiResult<List<CarAndPeopleRespDto>>> Handle(PeopleCommand request, CancellationToken cancellationToken)
        {
            try
            {
                var result = new ApiResult<List<CarAndPeopleRespDto>>();


                var data = PeopleSelect();
                result.data = await data;
                result.success(result.data);
                result.IsSuc = true;

                return result;
            }
            catch (Exception ex)
            {
                logger.LogError("事故人列表出错" + ex.Message);
                throw;
            }
        }
        public async Task<List<CarAndPeopleRespDto>> PeopleSelect()
        {
            try
            {

                var list = peoplerepository.Query(d => d.PeopleId > 0).ToList();
                var query = new List<CarAndPeopleRespDto>();
                foreach (var item in list)
                {
                    query.Add(new CarAndPeopleRespDto()
                    {
                        value = item.PeopleId,
                        label = item.PeopleName,
                    });
                }
                return query;

            }
            catch (Exception ex)
            {
                logger.LogError("事故人列表出错" + ex.Message);
                throw;
            }
        }
    }
}
